package crawlerThread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import crawler.Crawler;
import domain.StockVo;
import login.SimulationLogin;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import utils.JdbcUtil;
import utils.JsonUtil;

import java.util.List;

/**
 * @author sunzhihao2
 * @date 17:49 2018/5/24
 */
public class CrawlerThread extends Thread{
    // 通过构造方法给线程名字赋值
    public CrawlerThread(String name) {
        super(name);// 给线程名字赋值
    }


    // 为了保持概念ID的一致，票数要静态
    static List<Long> list = JdbcUtil.executeQuery();
    static int index = list.size() - 1;

    // 创建一个静态钥匙
    static Object ob = "lock";//值是任意的

    // 重写run方法，实现爬取操作
    @Override
    public void run() {
        //建立一次长连接，并登录包含token
        CloseableHttpClient closeableHttpClient = SimulationLogin.login();

        while (index >= 0) {
            synchronized (ob) {
                if (index >= 0) {
                    //获取概念的JSON数据
                    String result = JsonUtil.convertToConcept(Crawler.find(list.get(index),closeableHttpClient));
                    System.out.println(getName() + " 正在爬取第 " + index + " 个 ");
                    //同步操作
                    JSONObject jsonObject = JSON.parseObject(result);
                    String name = jsonObject.getString("name");
                    String desc = jsonObject.getString("desc");
                    String question_answers = jsonObject.getString("question_answers");
                    JdbcUtil.insertConcept(list.get(index),name,desc,question_answers);
                    index--;
                } else {
                    System.out.println("爬取结束");
                }
            }
            try {
                sleep(0);//休息一秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


}
